<template>
  <div>
    <form class="card comment-form">
      <div class="card-block">
        <textarea class="form-control" placeholder="Write a comment..." rows="3" v-model="value"></textarea>
      </div>
      <div class="card-footer">
        <img :src="user.image" class="comment-author-img" />
        <button :disabled="disabled" @click="hanlderAddComments" class="btn btn-sm btn-primary">Post Comment</button>
      </div>
    </form>

    <div class="card" v-for="comment in comments" :key="comment.id">
      <div class="card-block">
        <p class="card-text">{{comment.body}}</p>
      </div>
      <div class="card-footer">
        <nuxt-link :to="{
          name:'profile',
          params:{
            username:comment.author.username
          }
        }" class="comment-author">
          <img :src="comment.author.image" class="comment-author-img" />
        </nuxt-link>
        &nbsp;
        <nuxt-link :to="{
          name:'profile',
          params:{
            username:comment.author.username
          }
        }" class="comment-author">
        {{ comment.author.username }}
        </nuxt-link>
        <span class="date-posted">{{comment.createdAt | date('MMM DD, YYYY')}}</span>
          <span class="mod-options">
              <i class="ion-edit"></i>
              <i class="ion-trash-a" @click="hanlderdelComments(comment.id)"></i>
            </span>
      </div>
    </div>

    
  </div>
</template>

<script>
import { getComments, addComments, delComments }  from "@/api/article";
import { mapState } from 'vuex'
export default {
  name: "article-compenents",
    props:{
       slug:{
           type:String,
           required:true
       } 
    },
    data(){
      return {
       comments:[],
       value:'',
       disabled: false
      }
    },
    computed:{
     ...mapState(['user'])
    },
  async mounted(){
     this.hanlderquery()
  },
  methods:{
  async hanlderquery(){
  
      const { comments } =  await getComments(this.slug)
      console.log(comments,'------')
      this.comments = comments
  },
  async hanlderAddComments(){
    this.disabled = true
     await addComments(this.slug, {comment:{
       body:this.value
     }})
     this.value = ''
     this.hanlderquery()
     this.disabled = false
    },
   async hanlderdelComments(id){
     await delComments(this.slug, id)
     this.hanlderquery()
    }    
  }
};
</script>
<style lang='scss' scoped>
</style>
